<template>
  <div class="operation-log-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>{{ $t('operationLog.title') }}</h1>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>{{ $t('common.refresh') }}
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form 
        :model="searchForm" 
        :rules="searchRules" 
        ref="searchFormRef" 
        label-width="100px"
        class="search-form"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="{{ $t('operationLog.title') }}" prop="title">
              <el-input v-model="searchForm.title" placeholder="{{ $t('common.inputPlaceholder') }}" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="{{ $t('operationLog.operName') }}" prop="operName">
              <el-input v-model="searchForm.operName" placeholder="{{ $t('common.inputPlaceholder') }}" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="{{ $t('operationLog.status') }}" prop="status">
              <el-select v-model="searchForm.status" placeholder="{{ $t('common.selectPlaceholder') }}">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="{{ $t('common.timeRange') }}" prop="timeRange">
              <el-date-picker
                v-model="searchForm.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="{{ $t('common.startDate') }}"
                end-placeholder="{{ $t('common.endDate') }}"
                :disabled-date="disabledDate"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="search-button-row">
          <el-col :span="24" style="text-align: right">
            <el-button @click="handleReset">
              <el-icon><RefreshRight /></el-icon>{{ $t('common.reset') }}
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>{{ $t('common.search') }}
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 日志表格 -->
    <el-card class="log-table-card">
      <el-table 
        v-loading="loading" 
        :data="tableData" 
        stripe 
        border 
        fit 
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="id" label="{{ $t('operationLog.id') }}" width="80" />
        <el-table-column prop="title" label="{{ $t('operationLog.title') }}" min-width="120" />
        <el-table-column prop="operName" label="{{ $t('operationLog.operName') }}" min-width="100" />
        <el-table-column prop="operUrl" label="{{ $t('operationLog.operUrl') }}" min-width="180" show-overflow-tooltip />
        <el-table-column show-overflow-tooltip />
        <el-table-column prop="requestMethod" label="{{ $t('operationLog.requestMethod') }}" width="100" />
        <el-table-column prop="operatorType" label="{{ $t('operationLog.operatorType') }}" width="120">
          <template #default="scope">
            {{ getOperatorTypeText(scope.row.operatorType) }}
          </template>
        </el-table-column>
        <el-table-column prop="operIp" label="{{ $t('operationLog.operIp') }}" width="120" />
        <el-table-column prop="status" label="{{ $t('operationLog.status') }}" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="{{ $t('common.createTime') }}" width="180" />
        <el-table-column label="{{ $t('common.operation') }}" width="100" fixed="right">
          <template #default="scope">
            <el-button size="small" type="text" @click="handleViewDetail(scope.row)">
              <el-icon><View /></el-icon>{{ $t('common.view') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="pageNum"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    
    <!-- 详情模态框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="{{ $t('operationLog.detail') }}"
      width="60%"
      :before-close="handleDetailDialogClose"
    >
      <div class="detail-content">
        <!-- <el-descriptions title="{{ detailData.title }}" :column="1" border>
          <el-descriptions-item label="{{ $t('operationLog.id') }}">{{ detailData.id }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.operName') }}">{{ detailData.operName }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.operUrl') }}">{{ detailData.operUrl }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.requestMethod') }}">{{ detailData.requestMethod }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.operatorType') }}">{{ getOperatorTypeText(detailData.operatorType) }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.operIp') }}">{{ detailData.operIp }}</el-descriptions-item>
          <el-descriptions-item label="{{ $t('operationLog.status') }}">
            <el-tag :type="getStatusType(detailData.status)">{{ getStatusText(detailData.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="{{ $t('common.createTime') }}">{{ detailData.createTime }}</el-descriptions-item>
        </el-descriptions> -->
        
        <!-- <el-divider />> {{ $t('operationLog.operParam') }}</el-divider> -->
        <el-card class="log-code-card">
          <pre><code class="json-code">{{ formatJson(detailData.operParam) }}</code></pre>
        </el-card>
        
        <!-- <el-divider />> {{ $t('operationLog.jsonResult') }}</el-divider> -->
        <el-card class="log-code-card">
          <pre><code class="json-code">{{ formatJson(detailData.jsonResult) }}</code></pre>
        </el-card>
        
        <!-- <el-divider />> {{ $t('operationLog.errorMsg') }}</el-divider> -->
        <el-card v-if="detailData.errorMsg" class="log-error-card">
          <pre><code class="error-code">{{ detailData.errorMsg }}</code></pre>
        </el-card>
        <el-card v-else class="log-error-card">
          <span>{{ $t('operationLog.noError') }}</span>
        </el-card>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDetailDialogClose">{{ $t('common.close') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { 
  Search, 
  Refresh, 
  RefreshRight, 
  View 
} from '@element-plus/icons-vue'
import { useI18n } from 'vue-i18n'

export default {
  name: 'OperationLogPage',
  components: {
    Search,
    Refresh,
    RefreshRight,
    View
  },
  setup() {
    const { t } = useI18n()
    
    // 状态数据
    const tableData = ref([])
    const total = ref(0)
    const pageNum = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const detailDialogVisible = ref(false)
    const detailData = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      title: '',
      operName: '',
      status: '',
      timeRange: []
    })
    
    const searchFormRef = ref(null)
    
    // 状态选项
    const statusOptions = ref([
      { value: 0, label: t('operationLog.failure') },
      { value: 1, label: t('operationLog.success') }
    ])
    
    // 操作类型映射
    const operatorTypeMap = ref({
      1: t('operationLog.insert'),
      2: t('operationLog.update'),
      3: t('operationLog.delete'),
      4: t('operationLog.select'),
      5: t('operationLog.other')
    })
    
    // 加载日志数据
    const loadLogData = (params = {}) => {
      loading.value = true
      
      // 模拟API请求，实际项目中替换为真实API调用
      setTimeout(() => {
        // 模拟数据
        const mockData = generateMockLogData(
          pageNum.value, 
          pageSize.value, 
          searchForm,
          total.value
        )
        
        tableData.value = mockData.data
        total.value = mockData.total
        loading.value = false
      }, 500)
    }
    
    // 处理搜索
    const handleSearch = () => {
      searchFormRef.value?.validate((valid) => {
        if (valid) {
          pageNum.value = 1
          loadLogData()
        }
      })
    }
    
    // 处理重置
    const handleReset = () => {
      searchForm.title = ''
      searchForm.operName = ''
      searchForm.status = ''
      searchForm.timeRange = []
      pageNum.value = 1
      loadLogData()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadLogData()
    }
    
    // 处理当前页变化
    const handleCurrentChange = (val) => {
      pageNum.value = val
      loadLogData()
    }
    
    // 处理刷新
    const handleRefresh = () => {
      loadLogData()
    }
    
    // 处理查看详情
    const handleViewDetail = (row) => {
      detailData.value = row
      detailDialogVisible.value = true
    }
    
    // 处理详情对话框关闭
    const handleDetailDialogClose = () => {
      detailDialogVisible.value = false
    }
    
    // 获取操作类型文本
    const getOperatorTypeText = (type) => {
      return operatorTypeMap.value[type] || t('operationLog.other')
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      return status === 1 ? t('operationLog.success') : t('operationLog.failure')
    }
    
    // 获取状态类型（用于标签样式）
    const getStatusType = (status) => {
      return status === 1 ? 'success' : 'error'
    }
    
    // 格式化JSON
    const formatJson = (jsonStr) => {
      if (!jsonStr) return ''
      
      try {
        const json = typeof jsonStr === 'object' ? jsonStr : JSON.parse(jsonStr)
        return JSON.stringify(json, null, 2)
      } catch (e) {
        return jsonStr
      }
    }
    
    // 禁用日期选择（可选）
    const disabledDate = (time) => {
      return time.getTime() > Date.now() - 365 * 24 * 60 * 60 * 1000 // 只允许选择近一年
    }
    
    // 生成模拟日志数据（仅用于演示）
    const generateMockLogData = (page, size, search, totalCount) => {
      // 模拟总数据量
      totalCount = totalCount || 100
      
      // 模拟数据列表
      const data = []
      const startIndex = (page - 1) * size
      
      for (let i = startIndex; i < startIndex + size && i < totalCount; i++) {
        const status = i % 3 === 0 ? 0 : 1
        const operatorType = Math.floor(Math.random() * 5) + 1
        
        data.push({
          id: i + 1,
          title: `${t('operationLog.titlePrefix')} ${i + 1}`,
          operName: `用户${i + 100}`,
          operUrl: `/api/operation/${i + 1}`,
          requestMethod: ['GET', 'POST', 'PUT', 'DELETE'][Math.floor(Math.random() * 4)],
          operatorType,
          operIp: `192.168.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`,
          operParam: {
            id: i + 1,
            name: `参数${i + 1}`,
            page: page,
            size: size
          },
          jsonResult: {
            code: status === 1 ? 200 : 500,
            message: status === 1 ? t('operationLog.successMsg') : t('operationLog.failureMsg'),
            data: { result: i + 1 }
          },
          status,
          errorMsg: status === 0 ? `操作失败，错误代码：500，错误信息：模拟错误${i + 1}` : '',
          createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toLocaleString()
        })
      }
      
      return {
        data,
        total: totalCount
      }
    }
    
    // 监听搜索条件变化
    watch([() => searchForm.title, () => searchForm.operName, () => searchForm.status, () => searchForm.timeRange], 
      () => {
        if (pageNum.value === 1) {
          loadLogData()
        }
      }, { deep: true })
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadLogData()
    })
    
    return {
      t,
      tableData,
      total,
      pageNum,
      pageSize,
      loading,
      searchForm,
      searchFormRef,
      statusOptions,
      detailDialogVisible,
      detailData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleViewDetail,
      handleDetailDialogClose,
      getOperatorTypeText,
      getStatusText,
      getStatusType,
      formatJson
    }
  }
}
</script>

<style lang="scss" scoped>
.operation-log-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      margin: 0;
      font-size: 20px;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .search-form {
    .search-button-row {
      margin-top: 20px;
    }
  }
  
  .log-table-card {
    .log-code-card, .log-error-card {
      margin-top: 10px;
      white-space: pre-wrap;
      font-family: 'Courier New', Courier, monospace;
      font-size: 12px;
      overflow-x: auto;
      
      code {
        background-color: transparent;
      }
    }
    
    .json-code {
      color: #666;
    }
    
    .error-code {
      color: #f56c6c;
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>